import React, { useEffect, useState } from 'react';
import {
  Card,
  Row,
  Col,
  TreeSelect,
  DatePicker,
  Table,
  Statistic,
  message,
  Form,
  Button,
} from 'antd';
import {
  exportBillingStatistics,
  getCasOrganizationsShow,
  getBillingStatistics,
} from 'admin/servers/modules/Cas';
import type { ColumnsType } from 'antd/es/table';
import type { BillingStatisticsItem, OrganizationItem } from 'admin/schema/Cas';
import moment from 'moment';
import { convertToTree } from '../utils';
import { map } from 'lodash';

const { RangePicker } = DatePicker;

const Billing: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [organizations, setOrganizations] = useState<
    Omit<OrganizationItem, 'children' | 'description'>[]
  >([]);
  const [form] = Form.useForm();
  const [overview, setOverview] = useState<BillingStatisticsItem>();
  const [dataList, setDataList] = useState<BillingStatisticsItem[]>([]);

  const handleReset = () => {
    form.setFieldsValue({
      organization: map(organizations, 'id'),
      dateRange: [moment().subtract(7, 'days'), moment()],
    });
    getBillingStatistics({
      orgId: map(organizations, 'id'),
      startDate: moment().subtract(7, 'days').format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
    }).then(res => {
      if (res.status === '200') {
        setOverview(res.data.overview);
        setDataList([...res.data.dataList, res.data.subtotal]);
      }
    });
  };

  const handleFinish = (values: any) => {
    getBillingStatistics({
      orgId: values.organization,
      startDate: values.dateRange[0].format('YYYY-MM-DD'),
      endDate: values.dateRange[1].format('YYYY-MM-DD'),
    }).then(res => {
      if (res.status === '200') {
        setOverview(res.data.overview);
        setDataList([...res.data.dataList, res.data.subtotal]);
      }
    });
  };

  const handleExport = () => {
    const { organization, dateRange } = form.getFieldsValue();
    const startDate = dateRange[0].format('YYYY-MM-DD');
    const endDate = dateRange[1].format('YYYY-MM-DD');
    const fileName = `计费统计_${startDate}_${endDate}.xlsx`;

    exportBillingStatistics({
      orgId: organization,
      startDate: startDate,
      endDate: endDate,
    })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        message.success('导出成功');
      })
      .catch(error => {
        console.error('导出失败:', error);
        message.error('导出失败，请稍后重试');
      });
  };

  useEffect(() => {
    getCasOrganizationsShow()
      .then(res => {
        if (res.status === 200) {
          setOrganizations(res.data);
          form.setFieldsValue({
            organization: map(res.data, 'id'),
            dateRange: [moment().subtract(7, 'days'), moment()],
          });
          return getBillingStatistics({
            orgId: map(res.data, 'id'),
            startDate: moment().subtract(7, 'days').format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
          });
        }
      })
      .then(res => {
        if (res.status === '200') {
          setOverview(res.data.overview);
          setDataList([...res.data.dataList, res.data.subtotal]);
        }
      })
      .finally(() => {
        setLoading(false);
      });
    // eslint-disable-next-line
  }, []);

  const columns: ColumnsType<BillingStatisticsItem> = [
    {
      title: '日期',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '行业短信条数',
      dataIndex: 'industrySmsCount',
      key: 'industrySmsCount',
      sorter: (a, b) => a.industrySmsCount - b.industrySmsCount,
    },
    {
      title: '行业短信费用',
      dataIndex: 'industrySmsCost',
      key: 'industrySmsCost',
      sorter: (a, b) => a.industrySmsCost - b.industrySmsCost,
    },
    {
      title: '靶向短信条数',
      dataIndex: 'targetedSmsCount',
      key: 'targetedSmsCount',
      sorter: (a, b) => a.targetedSmsCount - b.targetedSmsCount,
    },
    {
      title: '靶向短信费用',
      dataIndex: 'targetedSmsCost',
      key: 'targetedSmsCost',
      sorter: (a, b) => a.targetedSmsCost - b.targetedSmsCost,
    },
    {
      title: '智能外呼时长',
      dataIndex: 'intelligentCallDuration',
      key: 'intelligentCallDuration',
      sorter: (a, b) => a.intelligentCallDuration - b.intelligentCallDuration,
    },
    {
      title: '智能外呼费用',
      dataIndex: 'intelligentCallCost',
      key: 'intelligentCallCost',
      sorter: (a, b) => a.intelligentCallCost - b.intelligentCallCost,
    },
  ];

  return (
    <div>
      <Card>
        <Form form={form} layout="inline" onFinish={handleFinish} style={{ marginBottom: 16 }}>
          <Form.Item label="单位" name="organization">
            <TreeSelect
              treeData={convertToTree(organizations)}
              maxTagCount={1}
              placeholder="请选择单位"
              showCheckedStrategy={TreeSelect.SHOW_ALL}
              treeCheckable
              allowClear
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              style={{ width: 300 }}
            />
          </Form.Item>
          <Form.Item label="日期" name="dateRange">
            <RangePicker style={{ width: 300 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>

        {overview && (
          <Card title="计费数据概览" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={4}>
                <Statistic title="行业短信条数" value={overview.industrySmsCount} />
              </Col>
              <Col span={4}>
                <Statistic title="行业短信费用" value={overview.industrySmsCost} />
              </Col>
              <Col span={4}>
                <Statistic title="靶向短信条数" value={overview.targetedSmsCount} />
              </Col>
              <Col span={4}>
                <Statistic title="靶向短信费用" value={overview.targetedSmsCost} />
              </Col>
              <Col span={4}>
                <Statistic title="智能外呼时长" value={overview.intelligentCallDuration} />
              </Col>
              <Col span={4}>
                <Statistic title="智能外呼费用" value={overview.intelligentCallCost} />
              </Col>
            </Row>
          </Card>
        )}

        <Card
          title="计费数据详情"
          extra={
            <Button type="primary" onClick={handleExport}>
              导出
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey="organization"
            loading={loading}
            pagination={false}
          />
        </Card>
      </Card>
    </div>
  );
};

export default Billing;
